package com.lukebang.service.serviceImpl;
import java.io.UnsupportedEncodingException;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lukebang.constant.Const;
import com.lukebang.constant.PayMethod;
import com.lukebang.constant.TypeOfIndent;
import com.lukebang.dao.IndentDao;
import com.lukebang.dao.InstallIndentDAO;
import com.lukebang.dao.MeasureIndentDAO;
import com.lukebang.dao.MerchantDAO;
import com.lukebang.dao.MerchantsWalletRecordDAO;
import com.lukebang.dao.RepairIndentDAO;
import com.lukebang.pojo.CityCostRule;
import com.lukebang.pojo.Indent;
import com.lukebang.pojo.InstallIndent;
import com.lukebang.pojo.MeasureIndent;
import com.lukebang.pojo.Merchant;
import com.lukebang.pojo.MerchantsWalletRecord;
import com.lukebang.pojo.RepairIndent;
import com.lukebang.service.ICityCostRuleService;
import com.lukebang.service.IPayService;
import com.lukebang.util.BuluResult;
import com.lukebang.util.DateUtils;
import com.lukebang.util.JsonUtil;
import com.lukebang.util.LuKeOrderNoUtil;
import com.lukebang.util.MD5Utils;
import com.lukebang.util.RSAUtils;
import com.lukebang.util.ClothCurtain.Arith;
import com.lukebang.util.jpush.JPushUtil;

/**
 * 
 * PayServiceImpl 上午11:16:24
 * 
 * Copyright zhaocj Inc. All rights reserved. Love ME Like Justin Bieber.
 */
@Service("paySER")
public class PayServiceImpl implements IPayService {
	private static Logger logger = LogManager.getLogger(PayServiceImpl.class.getName());
	@Resource
	private MerchantsWalletRecordDAO merchantsWalletRecordDAO;
	@Resource
	MeasureIndentDAO measureIndentDAO;
	@Resource
	private RepairIndentDAO repairIndentDAO;
	@Resource
	private MerchantDAO merchantDAO;
	@Resource
	InstallIndentDAO installIndentDAO;
	@Resource
	IndentDao IndentDao;
	@Resource
	ICityCostRuleService iCityCostRuleService;
	
	@Override
	public boolean insertRecharge(HttpServletRequest request, HttpSession session, Double money) {
		// 获取session中的merchants信息
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		// 插入钱包数据 但是出于未激活状态
		MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
		merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
		merchantsWalletRecord.setIndentId(0);// 充值时indentId的值为0
		String lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
				PayMethod.ALIPAY.getIndex(), TypeOfIndent.RECHARGE.getIndex());
		merchantsWalletRecord.setOrderNo(lukebang_order_num);
		merchantsWalletRecord.setMainMoney(money);
		merchantsWalletRecord.setWalletRecharge(money);// 充值金额
		merchantsWalletRecord.setFinalGetMoney(money);// 钱包最终得到金额
		merchantsWalletRecord.setAddMoney(0.00);
		merchantsWalletRecord.setType(TypeOfIndent.RECHARGE.getIndex());
		merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
		// 返回参数
		request.setAttribute("lukebang_tradeno", lukebang_order_num);
		request.setAttribute("lukebang_subject", "鹿客充值");
		request.setAttribute("lukebang_total_fee", String.valueOf(money));
		request.setAttribute("lukebang_body", "鹿客帮钱包充值");
		Map<String, String> extraMap = new HashMap<String, String>();
		extraMap.put("bussType", TypeOfIndent.RECHARGE.getName());
		request.setAttribute("extra_common_param", JSON.toJSONString(extraMap, SerializerFeature.UseSingleQuotes));
		return true;
	}
	//订单悬赏
	public boolean  rewardIndent(HttpServletRequest request, HttpSession session,Integer indentID, Double addPrice){
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		
		String lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),
				PayMethod.ALIPAY.getIndex(), TypeOfIndent.ADD_PRICE.getIndex());
		request.setAttribute("lukebang_tradeno", lukebang_order_num);
		request.setAttribute("lukebang_subject", "加价悬赏");
		request.setAttribute("lukebang_total_fee", String.valueOf(addPrice));
		request.setAttribute("lukebang_body", "加价悬赏");
		request.setAttribute("lukebang_returnUrl", "http://lukebang.com.cn/lukebang/indent/addMeasure.htm");
		Map<String, String> extraMap = new HashMap<String, String>();
		extraMap.put("bussType", TypeOfIndent.ADD_PRICE.getName());
		extraMap.put("indent", String.valueOf(indentID));
		extraMap.put("addPrice", String.valueOf(addPrice));
		request.setAttribute("extra_common_param", JSON.toJSONString(extraMap, SerializerFeature.UseSingleQuotes));
		
		
		MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
		merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
		merchantsWalletRecord.setIndentId(indentID);
		merchantsWalletRecord.setType(TypeOfIndent.ADD_PRICE.getIndex());//加价悬赏
		merchantsWalletRecord.setOrderNo(lukebang_order_num);
		merchantsWalletRecord.setAddMoney(addPrice);//加价悬赏额度
		merchantsWalletRecord.setFinalLostMoney(addPrice);
		merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
		return false;
	}
	
	
	// 余额支付
	@Override
	public BuluResult balancePayment(HttpServletRequest request, HttpSession session, Double totalMoney,String password, 
			Integer indentId,Double addPrice,Integer relievedBao,Integer crampetNumber,
			Integer fourClawNumber,Integer motorNumber,Integer type) throws Exception {
		BuluResult buluResult = new BuluResult();
		// 获取session中的merchants信息
		Merchant merchant = (Merchant) session.getAttribute(Const.SESSION_USER);
		//解密传输密码
		String descrypedPwd = null;
		RSAPrivateKey privateKey = (RSAPrivateKey) session.getAttribute("privateKey");
		descrypedPwd = RSAUtils.decryptByPrivateKey(password, privateKey);// 解密后的密码,password
		// 比对密码
		Map<String, Object> map = merchantDAO.selectMerchantPwd(merchant.getMerchantsId());
		String saltPassword = MD5Utils.GetMD5Code(descrypedPwd + merchant.getWeiyi());
		if (saltPassword.equals(map.get("password"))) {
			Double wallet = merchantDAO.selectWallet(merchant.getMerchantsId());
			// 比较balanceMoney和totalMoney的大小
			if (wallet >= totalMoney) {
				// 1.计算余额并更新钱包。
				Map<String, Object> updateWallet = new HashMap<>();
				updateWallet.put("merchantsId", merchant.getMerchantsId());
				updateWallet.put("wallet", wallet-totalMoney);
				merchantDAO.updateMerchantWallet(updateWallet);
				
				
				// 2。做交易记录
				MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
				merchantsWalletRecord.setMerchantsId(merchant.getMerchantsId());
				merchantsWalletRecord.setIndentId(indentId);
				merchantsWalletRecord.setMerchantsType(0);//商家
				merchantsWalletRecord.setAddMoney(addPrice);//加价悬赏
				
				merchantsWalletRecord.setFinalLostMoney(totalMoney);
				String lukebang_order_num = LuKeOrderNoUtil.getMerchantsOrderNo(merchant.getMerchantsId(),PayMethod.BALABCEPAY.getIndex(), TypeOfIndent.OTHER.getIndex());
				merchantsWalletRecord.setOrderNo(lukebang_order_num);
				merchantsWalletRecord.setRecordBeginTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
				merchantsWalletRecord.setRecordEndTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
				merchantsWalletRecord.setMethod(PayMethod.BALABCEPAY.getMethod());
				merchantsWalletRecord.setStatus(1);
				merchantsWalletRecord.setType(type);//纯配件订单
				merchantsWalletRecordDAO.insertMerchantsWalletRecord(merchantsWalletRecord);
				
				
				Indent indent=IndentDao.get(indentId);
				//3：更新订单状态和推送
				if(type==0 | type==1 |type==2){//测量安装维修支付订单
					Integer staus=installIndentDAO.selectInstallIndentStatus(indentId);
					if(staus !=0 && staus==4){//未支付-》等待工人接单
						indent.setRelievedBao(relievedBao);//安心包
						if(fourClawNumber!=null && fourClawNumber>0)
						indent.setSizhuagouNum(fourClawNumber);
						if(crampetNumber !=null && crampetNumber>0)
						indent.setBigouNum(crampetNumber);
						if(motorNumber !=null && motorNumber>0)
						indent.setMotorNum(motorNumber);
						if(addPrice !=null && addPrice>0)
						indent.setAddPrice(addPrice+indent.getAddPrice());//悬赏
						
						//计算安装配件价格
						CityCostRule rule=iCityCostRuleService.queryCostRuleByIndent(indentId);
						Double partsInstallFee=0.0;
						if(indent.getType()==0){ //测量
							;
						}else if(indent.getType()==1){//安装
							 partsInstallFee=crampetNumber*rule.getCrampetPrice()
									 +fourClawNumber*rule.getFourClawPrice()
									 +motorNumber*rule.getMotorPrice();
							 indent.setIndentPrice(indent.getWorkerRealPrice()+partsInstallFee);
							//低于起步价的话
							if(indent.getIndentPrice()<rule.getInstallStartingFare()){
								indent.setIndentPrice(rule.getInstallStartingFare());
							}
						}else if(indent.getType()==2){//维修
							 partsInstallFee=crampetNumber*rule.getCrampetPrice()
									 +fourClawNumber*rule.getFourClawPrice()
									 +motorNumber*rule.getMotorPrice();
							 indent.setIndentPrice(indent.getWorkerRealPrice()+partsInstallFee);
						}
						
						indent.setMerchantsPrice(totalMoney);//商家应付金额；
						indent.setStatus(0);//等待安装，测量，维修
						IndentDao.updateIndent(indent);
					}
				}else if(type==3){ //悬赏订单
					//修改订单的悬赏价格
					if(indent !=null){
						indent.setAddPrice(indent.getAddPrice()+addPrice);
						indent.setMerchantsPrice(addPrice+indent.getMerchantsPrice());
						IndentDao.updateIndent(indent);
					}
				}else{
					System.out.println("其他余额支付");
				}	
				//推送
				Map<String, Object> indentMap = measureIndentDAO.selectIndentByIndentIDForJpush(merchantsWalletRecord.getIndentId());
				Integer roomNumB = (Integer) indentMap.get("roomNumB");
				indentMap.put("roomNumB", roomNumB==null ? 0 : roomNumB);
				indentMap.put("motorNum",motorNumber==null ?0 : motorNumber);
				indentMap.put("bigouNum", crampetNumber==null ? 0 :crampetNumber);
				indentMap.put("sizhuagouNum", fourClawNumber==null ?0 :fourClawNumber);
				System.err.println("indentMap=========>"+indentMap);
				JPushUtil.JpushIndent(indentMap);// 通过极光推送订单
				
				buluResult.setStatus(0);
				buluResult.setData(wallet-totalMoney);
				buluResult.setMessage("支付成功");
			}else {
				buluResult.setStatus(1);
				buluResult.setMessage("余额宝余额不足，请选择其它支付方式!");
			}
		} else {
			buluResult.setStatus(1);
			buluResult.setMessage("密码不正确!");
		}
		return buluResult;
	}

	@Override
	public Integer modifyIndentStatus(HttpServletRequest request, String extra_common_param) {
		try {
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
			logger.error("支付宝交易号：{}", trade_no);
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
			logger.error("本次交易数据库订单号：{}", out_trade_no);
			MerchantsWalletRecord merchantsWalletRecord = new MerchantsWalletRecord();
			merchantsWalletRecord.setRecordEndTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
			merchantsWalletRecord.setTradeNo(trade_no);
			merchantsWalletRecord.setOrderNo(out_trade_no);
			merchantsWalletRecord.setStatus(1);
			merchantsWalletRecord.setMethod(PayMethod.ALIPAY.getMethod());
			int no = merchantsWalletRecordDAO.updateMerchantsWalletRecordByOrderNo(merchantsWalletRecord);
			logger.error("您修改了{}行", no);
			merchantsWalletRecord = merchantsWalletRecordDAO.selectMerchantsWalletRecordByOrderNo(out_trade_no);
			logger.error("支付成功的订单号ID:{}", merchantsWalletRecord.getIndentId());
			// 获取业务类型
			JSONObject parseObject = JSON.parseObject(extra_common_param, Feature.AllowSingleQuotes);
			String bussType = parseObject.getString("bussType").toString();
			if (bussType.equals(TypeOfIndent.MEASURE.getName())) {
				String relievedBao = parseObject.getString("relievedBao").toString();
				String addPrice = parseObject.getString("addPrice").toString();
				String originalMerchantPrice = parseObject.getString("originalMerchantPrice").toString();
				String originalIndentPrice = parseObject.getString("originalIndentPrice").toString();
				logger.error("bussType：{}", bussType);
				logger.error("relievedBao：{}", relievedBao);
				logger.error("addPrice：{}", addPrice);
				logger.error("originalMerchantPrice：{}", originalMerchantPrice);
				logger.error("originalIndentPrice：{}", originalIndentPrice);
				MeasureIndent measureIndent = new MeasureIndent();
				measureIndent.setIndentId(merchantsWalletRecord.getIndentId());
				measureIndent.setStatus(0);
				measureIndent.setAddPrice(Double.valueOf(addPrice));
				if (Integer.valueOf(relievedBao) == 1) {
					measureIndent.setRelievedBao(1);
					measureIndent.setMerchantsPrice(Double.valueOf(originalMerchantPrice) + 5);
				}
				no = measureIndentDAO.modifyByPrimaryKey(measureIndent);
				// 说明没有修改订单状态成功
				if (no > 0) {
					Map<String, Object> indentMap = measureIndentDAO
							.selectIndentByIndentIDForJpush(merchantsWalletRecord.getIndentId());
					Integer roomNumB = (Integer) indentMap.get("roomNumB");
					indentMap.put("roomNumB", roomNumB == null ? 0 : roomNumB);
					JPushUtil.JpushIndent(indentMap);// 通过极光推送订单
				}
			} else if (bussType.equals(TypeOfIndent.REPAIR.getName())) {
				Integer relievedBao = Integer.valueOf(parseObject.getString("relievedBao").toString());
				Double addPrice = Double.valueOf(parseObject.getString("addPrice").toString());
				Double originalMerchantPrice = Double
						.valueOf(parseObject.getString("originalMerchantPrice").toString());
				Double originalIndentPrice = Double.valueOf(parseObject.getString("originalIndentPrice").toString());
				Integer crampetNumber = Integer.valueOf(parseObject.getString("crampetNumber").toString());
				Integer fourClawNumber = Integer.valueOf(parseObject.getString("fourClawNumber").toString());
				Integer motorNumber = Integer.valueOf(parseObject.getString("motorNumber").toString());
				Double merchantAccessoryPrice = Double
						.valueOf(parseObject.getString("merchantAccessoryPrice").toString());
				Double indentAccessoryPrice = Double.valueOf(parseObject.getString("indentAccessoryPrice").toString());
				logger.error("bussType：{}", bussType);
				logger.error("relievedBao：{}", relievedBao);
				logger.error("addPrice：{}", addPrice);
				logger.error("originalMerchantPrice：{}", originalMerchantPrice);
				logger.error("originalIndentPrice：{}", originalIndentPrice);
				logger.error("crampetNumber：{}", crampetNumber);
				logger.error("fourClawNumber：{}", fourClawNumber);
				logger.error("motorNumber：{}", motorNumber);
				logger.error("merchantAccessoryPrice：{}", merchantAccessoryPrice);
				logger.error("indentAccessoryPrice：{}", indentAccessoryPrice);
				RepairIndent repairIndent = new RepairIndent();
				repairIndent.setIndentId(merchantsWalletRecord.getIndentId());
				repairIndent.setStatus(0);
				repairIndent.setAddPrice(addPrice);
				if (relievedBao == 1) {
					repairIndent.setRelievedBao(1);
					repairIndent.setMerchantsPrice(originalMerchantPrice + 5);
				} else {
					repairIndent.setMerchantsPrice(originalMerchantPrice);
				}
				repairIndent.setMerchantsPrice(Arith.add(repairIndent.getMerchantsPrice(), merchantAccessoryPrice));
				repairIndent.setIndentPrice(Arith.add(originalIndentPrice, indentAccessoryPrice));
				repairIndent.setSizhuagouNum(fourClawNumber);
				repairIndent.setMotorNum(motorNumber);
				repairIndent.setBigouNum(crampetNumber);
				logger.error("修改信息：{}", JsonUtil.toJson(repairIndent));
				no = repairIndentDAO.modifyByPrimaryKey(repairIndent);
				if (no > 0) {
					Map<String, Object> indentMap = repairIndentDAO
							.selectIndentByIndentIDForJpush(merchantsWalletRecord.getIndentId());
					Integer roomNumB = (Integer) indentMap.get("roomNumB");
					indentMap.put("roomNumB", roomNumB == null ? 0 : roomNumB);
					JPushUtil.JpushIndent(indentMap);// 通过极光推送订单
				}
				// 充值成功以后钱包余额增加相应的金额
			} else if (bussType.equals(TypeOfIndent.RECHARGE.getName())) {
				System.out.println("============进入充值回调========================");
				Merchant merchant = merchantDAO.selectMerchantByPrimaryKey(merchantsWalletRecord.getMerchantsId());
				System.out.println("merchant:"+merchant);
				if(merchant !=null && merchantsWalletRecord !=null){
					merchant.setMerchantsId(merchantsWalletRecord.getMerchantsId());
					merchant.setWallet(merchantsWalletRecord.getWalletRecharge()+merchant.getWallet());
					System.out.println("================金额：===============："+merchantsWalletRecord.getWalletRecharge()+merchant.getWallet());
					no = merchantDAO.modifyMerchantWalletByMerchant(merchant);
					System.out.println("no:"+no);
				}
				System.out.println("============结束充值回调========================");
			} else if (bussType.equals(TypeOfIndent.INSTALL.getName())) {
				Integer relievedBao = Integer.valueOf(parseObject.getString("relievedBao").toString());
				Double addPrice = Double.valueOf(parseObject.getString("addPrice").toString());
				Double originalMerchantPrice = Double
						.valueOf(parseObject.getString("originalMerchantPrice").toString());
				Double originalIndentPrice = Double.valueOf(parseObject.getString("originalIndentPrice").toString());
				Double merchantsRealPrice = Double.valueOf(parseObject.getString("merchantsRealPrice").toString());
				Double workerRealPrice = Double.valueOf(parseObject.getString("workerRealPrice").toString());
				
				Integer crampetNumber = Integer.valueOf(parseObject.getString("crampetNumber").toString());
				Integer fourClawNumber = Integer.valueOf(parseObject.getString("fourClawNumber").toString());
				Integer motorNumber = Integer.valueOf(parseObject.getString("motorNumber").toString());
				logger.error("bussType：{}", bussType);
				logger.error("relievedBao：{}", relievedBao);
				logger.error("addPrice：{}", addPrice);
				logger.error("originalMerchantPrice：{}", originalMerchantPrice);
				logger.error("originalIndentPrice：{}", originalIndentPrice);
				logger.error("crampetNumber：{}", crampetNumber);
				logger.error("fourClawNumber：{}", fourClawNumber);
				logger.error("motorNumber：{}", motorNumber);
				InstallIndent installIndent = new InstallIndent();
				installIndent.setIndentId(merchantsWalletRecord.getIndentId());
				installIndent.setStatus(0);
				installIndent.setMerchantsPrice(originalMerchantPrice);
				installIndent.setIndentPrice(originalIndentPrice);
				installIndent.setMerchantsRealPrice(merchantsRealPrice);
				installIndent.setWorkerRealPrice(workerRealPrice);
				installIndent.setAddPrice(addPrice);
				logger.error("an zhuang ding dan ====addPrice="+addPrice);
				installIndent.setRelievedBao(relievedBao);
				installIndent.setSizhuagouNum(fourClawNumber);
				installIndent.setMotorNum(motorNumber);
				installIndent.setBigouNum(crampetNumber);
				no = installIndentDAO.modifyByPrimaryKey(installIndent);
				if (no > 0) {
					Map<String, Object> indentMap = installIndentDAO
							.selectIndentByIndentIDForJpush(merchantsWalletRecord.getIndentId());
					Integer roomNumB = (Integer) indentMap.get("roomNumB");
					indentMap.put("roomNumB", roomNumB == null ? 0 : roomNumB);
					JPushUtil.JpushIndent(indentMap);// 通过极光推送订单
				}
			}else if(bussType.equals(TypeOfIndent.ADD_PRICE.getName())){
				//悬赏
				System.out.println("=============进入悬赏回调业务=====================");
				//修改钱包
				Merchant merchant = merchantDAO.selectMerchantByPrimaryKey(merchantsWalletRecord.getMerchantsId());
				if(merchant !=null && merchantsWalletRecord !=null){
					Double addPrice = Double.valueOf(parseObject.getString("addPrice"));
					if(addPrice==merchantsWalletRecord.getAddMoney()){
						if(merchant.getWallet()-merchantsWalletRecord.getAddMoney()>=0){
							merchant.setMerchantsId(merchantsWalletRecord.getMerchantsId());
							merchant.setWallet(merchant.getWallet()-merchantsWalletRecord.getAddMoney());
							no = merchantDAO.modifyMerchantWalletByMerchant(merchant);
							System.out.println("33333333333333");
							if(no>0){
								Indent indent=IndentDao.get(merchantsWalletRecord.getIndentId());
								System.err.println("---------------------------------------");
								if(indent!=null){
									System.err.println("=========jin ru==============");
									indent.setAddPrice(addPrice+indent.getAddPrice());
									logger.error("悬赏加价----indent是否更新该addPrice=======addPrice="+(addPrice+indent.getAddPrice()));
									IndentDao.updateIndent(indent);
									System.err.println("=========jin ru hou==============");
									
									//推送
									Map<String, Object> indentMap = installIndentDAO.selectIndentByIndentIDForJpush(merchantsWalletRecord.getIndentId());
									Integer roomNumB = (Integer) indentMap.get("roomNumB");
									indentMap.put("roomNumB", roomNumB == null ? 0 : roomNumB);
									JPushUtil.JpushIndent(indentMap);// 通过极光推送订单
								}
							}
						}	
				}
			}
		}
			logger.error("您修改了{}行", no);
			logger.error(JsonUtil.toJson(merchantsWalletRecord));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
